package com.jichangxiu.framework.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.jichangxiu.common.annotation.Scope;
import com.jichangxiu.common.context.JcxContext;
import com.jichangxiu.common.entity.rule.PostRule;
import com.jichangxiu.common.enums.ScopeType;

import java.util.ArrayList;
import java.util.List;

public class ScopeUtils {

    public static String getDataScope(Scope scope) {
        StringBuilder SqlBuilder = new StringBuilder();
        List<String> conditions = new ArrayList<>();
        List<PostRule> postRuleList = JcxContext.getPostRuleList();
        if (ObjectUtil.isNotNull(postRuleList)) {
            for (PostRule postRule : postRuleList) {
                String postId = postRule.getPostId();
                String postScope = postRule.getPostScope();
                if (conditions.contains(postScope))
                    continue;
                if (ScopeType.ALL.name().equalsIgnoreCase(postScope))
                    break;
                else if (ScopeType.CUSTOM.name().equalsIgnoreCase(postScope))
                    SqlBuilder.append(StrUtil.format(" OR {}.dept_by IN ( SELECT dept_id FROM sys_post_dept WHERE deleted != '1' AND tenant_id = '{}' AND post_id = '{}' ) ", scope.alias(), JcxContext.getTenantId(), postId));
                else if (ScopeType.DEPT.name().equalsIgnoreCase(postScope))
                    SqlBuilder.append(StrUtil.format(" OR {}.dept_by = '{}' ", scope.alias(), JcxContext.getDeptId()));
                else if (ScopeType.CHILD.name().equalsIgnoreCase(postScope))
                    SqlBuilder.append(StrUtil.format(" OR {}.dept_by IN ( SELECT id FROM sys_dept WHERE deleted != '1' AND enabled = true AND tenant_id = '{}' AND id = '{}' OR parent_id = '{}' )", scope.alias(), JcxContext.getTenantId(), JcxContext.getDeptId(), JcxContext.getDeptId()));
                else if (ScopeType.SELF.name().equalsIgnoreCase(postScope))
                    SqlBuilder.append(StrUtil.format(" OR {}.create_by = '{}' ", scope.alias(), JcxContext.getUserId()));
                conditions.add(postScope);
            }
        }
        if (StrUtil.isNotEmpty(SqlBuilder.toString()))
            return SqlBuilder.substring(4);
        else
            return SqlBuilder.toString();
    }

}
